<template>
<div>
    <el-row class="user-info-form" type="flex" justify="center">
        <el-col>
            <el-form label-position="top" :model="editForm" :rules="editFormRules" ref="editForm" @submit.native.prevent>
                <input type="hidden"  v-model="editForm.id">
                <el-form-item label="业主单位：" prop="name">
                    <el-select filterable
                      @change="unitSelectChange" 
                      v-model="editForm.organizationId" >
                      <el-option
                        v-for="item in orgOptions"
                        :key="item.organizationId"
                        :label="item.shortName"
                        :value="item.organizationId">
                      </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="名称：" prop="name">
                    <el-input v-model="editForm.name" auto-complete="off" placeholder="请输入名称"></el-input>
                </el-form-item>
                <el-form-item label="位置：" prop="location">
                    <el-input v-model="editForm.location" auto-complete="off" placeholder="请输入位置"></el-input>
                </el-form-item>
                <el-form-item label="电话：" prop="tel">
                    <el-input v-model="editForm.tel" auto-complete="off" placeholder="请输入电话"></el-input>
                </el-form-item>
                <el-form-item label="配置用户：" prop="relateUserOptions" id="select_relateUser">
                    <el-select multiple v-model="relateUserOptions" 
                        placeholder="请选择关联用户"
                        filterable 
                        :filter-method="getUnRelateUserList"
                        :loading="selectloading_user">
                        <el-option
                            v-for="item in unRelateUserOptions"
                            :key="item.accountName"
                            :label="item.name"
                            :value="item.accountName">
                        </el-option>
                        <el-pagination
                            @current-change="handleCurrentChange_user"
                            :current-page.sync="unRelateUserPageIndex"
                            small
                            layout="total, prev, pager, next"
                            :total="unRelateUserTotal">
                        </el-pagination>
                    </el-select>
                </el-form-item>
                <el-form-item label="视频监控：" prop="relateVideoOptions" id="select_relateVideo">
                    <el-select multiple v-model="relateVideoOptions" 
                        placeholder="请选择关联监控"
                        filterable 
                        :filter-method="getUnRelateVideoList"
                        :loading="selectloading_video">
                        <el-option
                            v-for="item in unRelateVideoOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                        <el-pagination
                            @current-change="handleCurrentChange_video"
                            :current-page.sync="unRelateVideoPageIndex"
                            small
                            layout="total, prev, pager, next"
                            :total="unRelateVideoTotal">
                        </el-pagination>
                    </el-select>
                </el-form-item>
                <el-form-item label="关联物联设备：" prop="relateFcOptions" id="select_relateFc">
                    <el-row :gutter="30">
                        <el-col :span="20">
                            <el-select multiple v-model="relateFcOptions" 
                                placeholder="请选择关联物联设备"
                                filterable 
                                :filter-method="getUnRelateFcList"
                                :loading="selectloading_fc">
                                <el-option
                                    v-for="item in unRelateFcOptions"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                                </el-option>
                                <el-pagination
                                    @current-change="handleCurrentChange_fcf"
                                    :current-page.sync="unRelateFcPageIndex"
                                    small
                                    layout="total, prev, pager, next"
                                    :total="unRelateFcTotal">
                                </el-pagination>
                            </el-select>
                        </el-col>
                        <el-col :span="4">
                            <el-button type="primary" icon="el-icon-plus" @click="selectMoreRelateFc"></el-button>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item label="室内地图：" prop="indoorMapId">
                    <el-select v-model="editForm.indoorMapId" 
                        placeholder="请选择室内地图" filterable @change="changeIndoorMap">
                        <el-option
                            v-for="item in indoorMapOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                            >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="室内地图楼层：" prop="indoorId">
                    <el-select filterable
                      v-model="editForm.indoorId" >
                      <el-option
                        v-for="item in indoorIdOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label-width="0" class="verifyidentity-button">
                    <el-button round @click="closeDialog()">取消</el-button>
                    <el-button type="primary" round @click="saveEdit('editForm')">确定</el-button>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
    <el-dialog
        :close-on-click-modal="false" 
        title="选择关联物联设备"
        width="600px"
        top='20vh'
        :visible.sync="dialogRelateFc"
        @close="closeRelateFcDialog"
        append-to-body
        v-dialogDrag>
        <el-row class="user-info-form" type="flex" justify="center">
            <el-col :span="24">
                <el-row style="padding: 10px 10px 10px 30px;">
                    <tree-select
                        placeholder="选择建筑物筛选设备"
                        v-model="fbsIds"
                        filterable
                        :width="200"
                        :data="buildList"
                        :defaultProps="buildDefaultProps"
                        :checkedKeys="defaultCheckedFbsId"
                        :nodeKey="buildNodeKey"
                        @popoverHide="handleNodeClick">
                    </tree-select>
                </el-row>
                <el-row type="flex" justify="center">
                    <el-transfer v-model="selectRelateFcOptions" :data="allUnRelateFcOptions"  
                        :titles="['未选择', '已选择']"
                        :props="{
                            key: 'id',
                            label: 'name'
                        }"></el-transfer>
                </el-row>
                <el-row class="verifyidentity-button">
                    <el-button round @click="dialogRelateFc=false">取消</el-button>
                    <el-button type="primary" round @click="determineRelateFc">确定</el-button>
                </el-row>
            </el-col>
        </el-row>
    </el-dialog>
</div>
</template>

<script>
import util from '@/utils/util'
import TreeSelect from '@/libs/TreeSelect/Main'
import { getOrgList, getIndoorInfoList} from '@/api/org'
import { qnToken} from '@/api/api'
import {selectVenuesRelateInfo,selectVenuesUnRelateInfo,saveNineSmallVenues} from '@/api/venues'
import { getFbsTree } from '@/api/assets'

export default {
  name:'NineSmallVenuesForm',
  props: {
    editInfo: {
        type: Object,
        required: false
    },
    closeDialog: {
        type: Function,
        required: true
    },
  },
  components: {
      TreeSelect
  },
  data() {
    return {
        defaultImg: this.GLOBAL.defaultImg,
        util:util,
        orgOptions: [],
        relateFcOptions: [], // 关联探测器
        relateUserOptions: [], // 关联人
        relateVideoOptions: [], // 关联视频
        relateFcNames: [], // 关联探测器
        relateUserNames: [], // 关联人
        relateVideoNames: [], // 关联视频
        unRelateFcOptions: [], // 未关联探测器
        unRelateUserOptions: [], // 未关联人
        unRelateVideoOptions: [], // 未关联视频
        indoorMapOptions:[], //室内地图
        indoorIdOptions:[], //室内地图楼层
        selectloading_fc: false,
        selectloading_video: false,
        selectloading_user: false,
        unRelateFcPageIndex: 1,
        unRelateFcTotal: 0,
        unRelateUserPageIndex: 1,
        unRelateUserTotal: 0,
        unRelateVideoPageIndex: 1,
        unRelateVideoTotal: 0,
        editForm: {
            id: 0,
            organizationId: ''/* this.$store.state.userinfo.org.id */,
            name:'',
            fcfsStr:'',
            videoStr:'',
            userStr:'',
            location:'',
            tel:'',
            indoorMapId:'',
            indoorId:'',
        },
        editFormRules: {
            name: [
                { required: true, message: '请输入名称', trigger: 'blur' },
            ],
            location: [
                { required: true, message: '请输入位置', trigger: 'blur' },
            ],
            organizationId: [
              { required: true, message: '请选择业主单位', trigger: 'change' }
            ],
        },
        dialogRelateFc: false,
        // 建筑物
        fbsIds: '',
        buildList: [],
        buildDefaultProps: {
            children: 'nodes',
            label: 'text',
            value: 'id'
        },
        defaultCheckedFbsId: [],
        buildNodeKey: 'id',
        allUnRelateFcOptions: [],
        selectRelateFcOptions: [] // 已选择的关联物联设备
    }
  },
  created() {
      let that = this
      //绑定下拉框
      getOrgList({queryType: 0}).then((data)=>{
        //  默认选择第一个单位
        this.editForm.organizationId = data.data[0].organizationId
        this.orgOptions.push.apply(this.orgOptions,data.data)

        let infoObj = this.editInfo
        if(infoObj.id) {//编辑
            this.editForm.organizationId = infoObj.organizationId
            this.editForm.id = infoObj.id
            this.editForm.name = infoObj.name
            this.editForm.location = infoObj.location
            this.editForm.tel = infoObj.tel
            this.editForm.indoorMapId = infoObj.indoorMapId
            this.editForm.indoorId = infoObj.indoorId
            selectVenuesRelateInfo({
            venuesId : infoObj.id
            }).then((result) => {
                if(result.data)
                    that.relateFcOptions = util.ilinkArrHandle.getArrObjAttrToArr(result.data['fcfsList'],"id")
                    that.relateUserOptions =  util.ilinkArrHandle.getArrObjAttrToArr(result.data['userList'],"accountName")
                    that.relateVideoOptions = util.ilinkArrHandle.getArrObjAttrToArr(result.data['videoList'],"id")
                    that.relateFcNames = util.ilinkArrHandle.getArrObjAttrToArr(result.data['fcfsList'],"name")
                    that.relateUserNames =  util.ilinkArrHandle.getArrObjAttrToArr(result.data['userList'],"name")
                    that.relateVideoNames =  util.ilinkArrHandle.getArrObjAttrToArr(result.data['videoList'],"name")
                    this.dealSelectCb()
            })
        }
        this.getUnRelateUserList()
        this.getUnRelateVideoList()
        this.getUnRelateFcList()
        this.getIndoorInfoOptions()
        this.getAllUnRelateFcList()
        this.getBuildList()
      })
  },
  methods: {
    unitSelectChange(){
      // 清空关联物联设备
      this.relateFcOptions = []
      this.relateUserOptions = [] // 关联人
      this.relateVideoOptions = [] // 关联视频

      this.getUnRelateUserList()
      this.getUnRelateVideoList()
      this.getUnRelateFcList()
      this.getAllUnRelateFcList()
      this.getIndoorInfoOptions()
      this.getBuildList()
    },
    //获取室内地图列表
    getIndoorInfoOptions(){
        let that = this
        let parames = {
            queryType: 0,
            pageIndex: 0,
            pageSize: 0,
            types: '0,1,2,3'
        }
        getIndoorInfoList(parames).then(res => {
            that.indoorMapOptions = res.data
            that.initIndoor()
        })
    },
    initIndoor(){
        let self = this
        let deployInfo = ''
        let value = Number(self.editForm.indoorMapId)
        let optinos = self.indoorMapOptions;
        for(let i = 0 ;i<optinos.length;i++){
            if(optinos[i].id === value){
                deployInfo  = optinos[i].deployInfo
                break
            }
        }
        if(deployInfo){
            self.indoorIdOptions = JSON.parse(deployInfo);
        }
    },
    changeIndoorMap(value){
        let self = this
        let deployInfo = ''
        let optinos = self.indoorMapOptions;
        for(let i = 0 ;i<optinos.length;i++){
            if(optinos[i].id === value){
                deployInfo  = optinos[i].deployInfo
                break
            }
        }
        if(deployInfo){
            self.indoorIdOptions = JSON.parse(deployInfo);
            self.editForm.indoorId= ''
        }
    },
    //处理编辑多选分页下拉框回选
    dealSelectCb(){
        let that = this
          /*
         * 解决带分页的下拉框回显值不在首页无法显示label问题
         */
        that.$nextTick(() => {
            if(that.editForm.id) {
                let $tags = $('#select_relateUser .el-select__tags').find('.el-select__tags-text')
                for (let i=0, len=$tags.length; i < len; i++) {
                    $tags[i].innerText = that.relateUserNames[i]
                }
                let $tags1 = $('#select_relateVideo .el-select__tags').find('.el-select__tags-text')
                for (let i=0, len=$tags1.length; i < len; i++) {
                    $tags1[i].innerText = that.relateVideoNames[i]
                }
                let $tags2 = $('#select_relateFc .el-select__tags').find('.el-select__tags-text')
                for (let i=0, len=$tags2.length; i < len; i++) {
                    $tags2[i].innerText = that.relateFcNames[i]
                }
            }
            return false
        })
    },
    //用户多选框
    handleCurrentChange_user(currentpage) {
        this.unRelateUserPageIndex = currentpage
        this.getUnRelateUserList($('#select_relateUser .el-select__input').val(), true)
    },
    getUnRelateUserList(name, pageChange) {
      this.selectloading_user = true
      // 重新搜索时页码复原   
      if(!pageChange) {
        this.unRelateUserPageIndex = 1
      }
      selectVenuesUnRelateInfo({
            isEncrypt: false,
            venuesId:this.editForm.id,
            relateObjType:3,
            queryType: 1,
            isSelectCureent:1,
            organizationId: this.editForm.organizationId,
            parentId: 0,
            pageIndex: this.unRelateUserPageIndex - 1,
            pageSize: 10,
            name: name || ''
      }).then(res => {
        this.unRelateUserOptions = res.data
        this.unRelateUserTotal = res.total
        this.selectloading_user = false
      })
    },
    //视频多选框
    handleCurrentChange_video(currentpage) {
        this.unRelateVideoPageIndex = currentpage
        this.getUnRelateVideoList($('#select_relateVideo .el-select__input').val(), true)
    },
    getUnRelateVideoList(name, pageChange) {
      this.selectloading_video = true
      // 重新搜索时页码复原   
      if(!pageChange) {
        this.unRelateVideoPageIndex = 1
      }
      selectVenuesUnRelateInfo({
            isEncrypt: false,
            venuesId:this.editForm.id,
            relateObjType:2,
            queryType: 1,
            isSelectCureent:1,
            organizationId: this.editForm.organizationId,
            parentId: 0,
            pageIndex: this.unRelateVideoPageIndex - 1,
            pageSize: 10,
            name: name || ''
      }).then(res => {
        this.unRelateVideoOptions = res.data
        this.unRelateVideoTotal = res.total
        this.selectloading_video = false
      })
    },
    //消防设施多选框
    handleCurrentChange_fcf(currentpage) {
        this.unRelateFcPageIndex = currentpage
        this.getUnRelateFcList($('#select_relateFc .el-select__input').val(), true)
    },
    getUnRelateFcList(name, pageChange) {
      this.selectloading_fc = true
      // 重新搜索时页码复原   
      if(!pageChange) {
        this.unRelateFcPageIndex = 1
      }
      selectVenuesUnRelateInfo({
            isEncrypt: false,
            venuesId:this.editForm.id,
            relateObjType:1,
            queryType: 1,
            isSelectCureent:1,
            organizationId: this.editForm.organizationId,
            parentId: 0,
            pageIndex: this.unRelateFcPageIndex - 1,
            pageSize: 10,
            name: name || ''
      }).then(res => {
        this.unRelateFcOptions = res.data
        this.unRelateFcTotal = res.total
        this.selectloading_fc = false
      })
    },
    getAllUnRelateFcList() {
      selectVenuesUnRelateInfo({
            isEncrypt: false,
            venuesId:this.editForm.id,
            relateObjType:1,
            queryType: 0,
            isSelectCureent:1,
            organizationId: this.editForm.organizationId,
            parentId: 0,
            name: '',
            fbsId: this.fbsIds
      }).then(res => {
        this.allUnRelateFcOptions = res.data
      })
    },
    saveEdit(formName) {
        // 阻止事件冒泡
        event.stopPropagation()
        let that = this
        that.$refs[formName].validate((valid) => {
          if (valid) {
            let parames = that.editForm
            let fcArr = [];
            $.each(that.relateFcOptions,(index,key)=>{
                fcArr.push({
                    id: key
                })
            })
            parames.fcfsStr =JSON.stringify(fcArr);
            let videoArr = [];
            $.each(that.relateVideoOptions,(index,key)=>{
                videoArr.push({
                    id: key
                })
            })
            parames.videoStr =JSON.stringify(videoArr)    
            let userArr = [];
            $.each(that.relateUserOptions,(index,key)=>{
                userArr.push({
                    accountName: key
                })
            })
            parames.userStr =JSON.stringify(userArr);
            saveNineSmallVenues(parames).then(res => {
                if(res.status === 200) {
                    that.$message({
                        message: '保存成功！',
                        type: 'success'
                    })
                    that.closeDialog(true)
                } else {
                    that.$message({
                        message: res.info,
                        type: 'warning'
                    })
                }
            });
          } else {
              return false
          }
        });
    },
    // 打开关联物联设备多选弹框
    selectMoreRelateFc() {
        this.fbsIds = ''
        this.defaultCheckedFbsId = []
        this.selectRelateFcOptions = this.relateFcOptions
        this.dialogRelateFc = true

    },
    getBuildList() {
      let that = this
      getFbsTree({
        organizationId: that.editForm.organizationId
      }).then(res => {
        that.buildList = res.data.length === 0 ? [] : res.data
      })
    },
    handleNodeClick(checkedIds, checkedData) {
        let that= this
        if(checkedIds && checkedIds !== this.fbsIds) {
            this.fbsIds = checkedIds
            this.getAllUnRelateFcList(checkedIds)
        }
    },
    closeRelateFcDialog() {
        this.dialogRelateFc = false
        this.fbsIds = ''
        this.defaultCheckedFbsId = []
        this.getAllUnRelateFcList()
    },
    // 确定选择
    determineRelateFc() {
        this.relateFcOptions = this.selectRelateFcOptions
        this.dialogRelateFc = false
    }
  }
}
</script>
